<template>
    <div class="container-box">
        <div style="height: 98px;"></div>
        <!-- serch -->
        <div class="bgfffs filter_box" :style="contentStyleObj">
            <page-filter :className="className" lableWidth="70px" ref="from" :query.sync="filterInfo.query"
                :filter-list="filterInfo.list" :list-type-info="listTypeInfo" @handleClick="handleClick"
                @handleEvent="handleEvent" @upenter="upenter">
            </page-filter>
        </div>

        <div class="bgfff" ref="tableWrapper">
            <div style="padding: 10px 10px">
                <page-table :checkBox="false" :pager="false" ref="table" :tabIndex="true" :dataText="dataText"
                    v-loading="loading" :init-curpage="tableInfo.initCurpage" :data.sync="tableInfo.data"
                    :pageParm="pageParm" :query="filterInfo.query" :field-list="tableInfo.fieldList"
                    :list-type-info="listTypeInfo" :showSummary="showSummary" :getSummaries="getSummaries"
                     @handleClick="handleClick" @handleEvent="handleEvent">
                     <template v-slot:col-invoice_detail="scope">
                            <div v-if="scope.row.invoice_detail != ''" slot="reference" style="cursor: pointer;color: #409eff;"
                            @click="showInvoiceDetail(scope.row)">
                                {{ scope.row.invoice_detail }}
                                <i class="el-icon-s-order"></i>
                            </div>
                        </template>
                </page-table>
            </div>
        </div>
        <el-dialog title="开票记录" :visible.sync="record" :close-on-press-escape="false" :close-on-click-modal="false"
      width="800px">
      <div class="recordTable">
        <el-table :data="recordTableData" :header-cell-style="{
          background: 'rgba(238,241,246,1)',
          fontSize: '12px'
        }" class="toppp-table" style="width: 100%; font-size: 12px">
          <el-table-column type="index" label="序号" align="center"></el-table-column>
          <el-table-column prop="add_time" align="center" label="申请时间"></el-table-column>
          <el-table-column prop="amount" align="center" label="申请金额"></el-table-column>
          <el-table-column prop="name" align="center" label="公司名称"></el-table-column>
          <el-table-column prop="tax_number" align="center" label="税号"></el-table-column>
          <el-table-column prop="address" align="center" label="注册地址"></el-table-column>
          <el-table-column prop="bank_name" align="center" label="开户行"></el-table-column>
          <el-table-column prop="bank_account" align="center" label="账号"></el-table-column>
          <el-table-column prop="remark" align="center" label="备注"></el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="record = false">关 闭</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>

import PageDialog from "@/components/PageDialog";
import PageFilter from "@/components/PageFilter/index";
import PageTable from "@/components/PageTable/index";
import { formatter } from "@/utils/index";
import {
    paymentList,// 列表
    getInvoiceParam,//筛选基础参数
    getInvoiceDetail,//发票记录
} from '@/api/bill'
export default {
    name: "payStatPage",
    components: {
        PageFilter,
        PageDialog,
        PageTable
    },
    data () {
        return {
            id: null,
            fullYear: new Date().getFullYear(),
            month: new Date().getMonth() + 1,
            loading: false,
            billLading: '',
            addId: [],
            dataText: "",
            enter: {},
            checked: false,
            showSummary: false,
            isChecked: true,
            tax_list: [],//税率可选项
            amount_total: 0,
            pay_amount: 0,
            not_pay_amount: 0,
            invoice_amount: 0,
            not_invoice_amount: 0,
            apply_amount_total: 0,
            billAmount: 0,
            billTax: '',
            billType: 0,
            settlement_time: "",
            record: false,
            recordTableData: {},
            contentStyleObj: {
                height: "100%"
            },
            refresh: false,
            relation: false,
            relationMixedCost: [],
            labelPosition: 'right',
            show: false,
            invoiceForm: {
                settlement_time: "",//结算账期
                tax_ratio: "",//税率
                invoice_type: 0,//发票类型
                amount: "",//开票金额
                task: [],//任务信息
                name: "",
                tax_number: "",
                address: '',
                bank_name: '',
                bank_account: '',
                car_number: "",
                goods: "",
                start_address: "",
                end_address: "",
                remark: "",
            },
            showInvoice: false,
            showReconciliation: false,
            className: "forms",
            // 相关列表
            listTypeInfo: {
                group_id_list: [], 
            },
            // 过滤相关配置
            filterInfo: {
                query: {
                    group_id: "", // 否 string 发布企业
                    settlement_time: "",
                },
                list: [
                    {
                        type: "select",
                        label: "发布企业",
                        value: "group_id",
                        list: "group_id_list",
                        key: "发布企业"
                    },
                    {
                        type: "month",
                        dateType: "month",
                        format: "yyyy-MM",
                        label: "运费账期",
                        value: "settlement_time",
                        clearable: false,
                        key: "运费账期",
                    },
                    {
                        type: "button",
                        label: "搜索",
                        btType: "primary",
                        event: "search",
                        show: true
                    },
                ]
            },
     
            // 分页参数
            pageParm: {
                tableHeight: "52vh", // 表格最大高度
                total: 0, // 总条数
                loading: true, // 加载动画
                pagesizes: [20, 50, 100], // 分页数量列表
                query: {
                    // 查询条件
                    // page: 1, // 当前页
                    // limit: 20 // 每页条数
                }
            },
            // 表格相关
            tableInfo: {
                refresh: 1,
                initCurpage: 1,
                data: [],
                fieldList: [
                    { label: "状态", value: "status_text", width: "100px", fixed: true },
                    { label: "费用", value: "amount_name", width: "130px" },
                    { label: "总金额", value: "amount", width: "110px" },
                    { label: "已收款", value: "pay_amount", width: "110px" },
                    { label: "未收款", value: "not_pay_amount", width: "110px" },
                    { label: "已开票金额", value: "invoice_amount", width: "110px" },
                    { label: "未开票金额", value: "not_invoice_amount", width: "110px" },
                    { label: "开票记录", value: "invoice_detail", type: "slot"},
                ],
            },
        };
    },
    created () {
        let date = new Date();
        this.settlement_time = date.getFullYear() + "-" + (date.getMonth() + 1);
        this.filterInfo.query.settlement_time = this.settlement_time;
        this.init({ ...this.pageParm.query, ...this.filterInfo.query });
        this.getParamList();
        //this.getHeight();
        this.fetTableHeight()
        this.upenter();
        //window.addEventListener("resize", this.getHeight);
    },
    //enter事件 与点击查询按钮功能一致
    updated () {
        var that = this;
    },
    activated () {
        this.init(this.filterInfo.query);
        this.getParamList();
        this.upenter();
        this.refresh = false;
    },
    deactivated () {
        this.refresh = true;
    },
    filters: {
        formatter (time) {
            let date = new Date(time),
                text = "";
            if (time !== "") return (text = formatter(date, "yyyy-MM"));
            return text;
        }
    },
    computed: {
    },
 

    methods: {

        //合计
        getSummaries (param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 2) {
                    sums[index] = "合计：";
                    return;
                }
                if (index === 3) {
                    sums[index] = this.amount_total;
                    return;
                }
                if (index === 4) {
                    sums[index] = this.pay_amount;
                    return;
                }
                if (index === 5) {
                    sums[index] = this.not_pay_amount;
                    return;
                }
                if (index === 6) {
                    sums[index] = this.invoice_amount;
                    return;
                }
                if (index === 7) {
                    sums[index] = this.not_invoice_amount;
                    return;
                }

            });
            this.$nextTick(() => {
                this.$refs.table.$refs.table.doLayout();
                this.$refs.table.$refs.table.bodyWrapper.scrollLeft = 0;
            });
            return sums;
        },
        unique (arr) {
            const res = new Map();
            return arr.filter(a => !res.has(a) && res.set(a, 1));
        },
        arrayAminusB (arrA, arrB) {
            return arrA.filter(v => !arrB.includes(v));
        },
        //enter 事件防止全局触发
        upenter () {
            var that = this;
            document.onkeydown = e => {
                //13表示回车键，baseURI是当前页面的地址，为了更严谨，也可以加别的，可以打印e看一下
                if (e.keyCode === 13 && e.target.baseURI.match("receivableVerification") && !that.showInvoice && !that.showReconciliation && !that.showDestroy && !that.dialogInfo.visible) {
                    console.log("回车事件", that.dialogInfo.visible);
                    //回车后执行搜索方法
                    that.filterInfo.query.page = 1;
                    that.pageParm.query.page = 1;
                    that.init(that.filterInfo.query);
                }
            };
        },
        openWind () {
        },
        getHeight () {
            if (this.contentStyleObj.height == "100%") {
                var height =
                    window.innerHeight - parseInt(this.contentStyleObj.height) - 40;
            } else {
                var height =
                    window.innerHeight - parseInt(this.contentStyleObj.height) - 146;
            }
            this.pageParm.tableHeight = height + "px";
        },
        // 重置table高度
        resetHeight () {
            return new Promise((resolve, reject) => {
                this.tableH = 0
                resolve()
            })
        },
        // 设置table高度
        fetTableHeight () {
            this.resetHeight().then(res => {
                this.pageParm.tableHeight = this.$refs.tableWrapper.getBoundingClientRect().height  + 75
                // 设置最小高度，确保表格可以正常显示
                // this.tableH = Math.max(containerHeight - 10, 200); // 最小300px
            })
        },
        //获取本月月初 月末
        // getonemonth() {
        //   var nowDate = new Date();
        //   var fullYear = nowDate.getFullYear();
        //   var month = nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月
        //   var endOfMonth = new Date(fullYear, month, 0).getDate(); // 获取本月最后一天

        //   this.settlement_time =  nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1);
        //   this.filterInfo.query.settlement_time =  nowDate.getFullYear();
        // },
        //格式化年月日
        getFullDate (targetDate) {
            var D, y, m, d;
            if (targetDate) {
                D = new Date(targetDate);
                y = D.getFullYear();
                m = D.getMonth() + 1;
                d = D.getDate();
            } else {
                y = fullYear;
                m = month;
                d = date;
            }
            m = m > 9 ? m : "0" + m;
            d = d > 9 ? d : "0" + d;
            return y + "-" + m + "-" + d;
        },
        init (data) {
            if (data.group_id != '') {
                this.loading = true;
                let formData = new FormData();
                formData.append('group_id', data.group_id);
                formData.append('settlement_time', data.settlement_time);
                paymentList(formData).then(res => {
                this.showSummary = true;
                this.tableInfo.data = [];
                this.tableInfo.data = res.data.data;
                if (this.tableInfo.data.length === 0) {
                    this.dataText = "暂无数据";
                    this.amount_total = 0.00;
                }
                this.amount_total = res.data.total.amount;
                this.pay_amount = res.data.total.pay_amount;
                this.not_pay_amount = res.data.total.not_pay_amount;
                this.invoice_amount = res.data.total.invoice_amount;
                this.not_invoice_amount = res.data.total.not_invoice_amount;
                this.pageParm.total = res.data.total;
                this.loading = false;
            });
            }else{
                this.dataText = "暂无数据";
                this.amount_total = 0.00;
            }

           
        },

        getCurrentDate () {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        getCurrentMonth () {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            return `${year}-${month}`;
        },

        getParamList () {
            getInvoiceParam().then(res => {
                let {
                    group_id,
                } = res.data;
                group_id = group_id.map(v => {
                    return {
                        key: v.value,
                        value: v.name
                    };
                });
                this.listTypeInfo.group_id_list = group_id;
                
            });

        },
        showInvoiceDetail (row) {
            this.record = true
            const formData = new FormData()
            formData.append('id', row.id)
            getInvoiceDetail(formData).then(res => {
                this.recordTableData = res.data.list
            })
        },
        handleClick (event, data) {
            console.log(event, data);
            switch (event) {
                case "remove":
                    break;
                case "close":
                    break;
                case "search":
                if (this.filterInfo.query.group_id == "") {
                        this.$message({
                            type: "error",
                            message: "请选择发布企业！"
                        });
                        return
                    }
                    this.pageParm.query.page = 1;
                    this.filterInfo.query.page = 1;
                    this.init(this.filterInfo.query);
                    break;
                case "reset":
                    for (let i in this.filterInfo.query) {
                        this.filterInfo.query[i] = "";
                    }
                    this.filterInfo.query.page = 1;
                    this.filterInfo.query.limit = 20;
                    this.pageParm.query.page = 1;
                    this.pageParm.query.limit = 20;
                    let datas = {};
                    datas = Object.assign({}, this.pageParm.query, this.filterInfo.query);
                    this.init(datas);
                    break;
            }
        },
        handleEvent (event, data, label) {
            let datas = {};
            console.log('事件---', event)
            console.log('数据信息---', data)
            switch (event) {
                case "rowClick":
                    break;
                // 分页改变当前页
                case "curPage":
                    if (!data) return;
                    this.pageParm.query.page = data;
                    this.filterInfo.query.page = data;
                    datas = Object.assign({}, this.pageParm.query, this.filterInfo.query);
                    this.init(datas);
                    break;
                // 分页列表
                case "pageSize":
                    if (!data) return;
                    this.pageParm.query.limit = data;
                    this.filterInfo.query.limit = data;
                    this.pageParm.query.page = 1;
                    this.filterInfo.query.page = 1;
                    datas = Object.assign({}, this.pageParm.query, this.filterInfo.query);
                    this.init(datas);
                    break;
                default:
                    break;
            }
        },
        tableHandleEvent (event, data, label) {
            let datas = {};
            switch (event) {
                case "rowClick":
                    break;
                default:
                    break;
            }
        },
    },
    //   destroyed() {
    //     window.removeEventListener("resize", this.getHeight);
    //   }
};
</script>
<style lang="scss">
.flex-div {
    display: flex;
    /* justify-content: space-between; */
    flex-direction: row;
    align-items: center;
}

.search-div {
    position: relative;
    width: 300px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

/* 去掉input尾部上下小箭头 start */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    -o-appearance: none !important;
    -ms-appearance: none !important;
    appearance: none !important;
    margin: 0;
}

input[type="number"] {
    -webkit-appearance: textfield;
    -moz-appearance: textfield;
    -o-appearance: textfield;
    -ms-appearance: textfield;
    appearance: textfield;
}

/* 去掉input尾部上下小箭头 end */
</style>
<style lang="scss" scoped>


.salecss {
    white-space: nowrap;
    /*强制span不换行*/
    display: inline-block;
    /*将span当做块级元素对待*/
    width: 60px;
    /*限制宽度*/
    overflow: hidden;
    /*超出宽度部分隐藏*/
    text-overflow: ellipsis;
    /*超出部分以点号代替*/
    line-height: 0.9;
    /*数字与之前的文字对齐*/
}

.salecss:hover {
    cursor: pointer;
}

.bgfff {
    background: #fff;
    flex: 1;
}

.bgfffs {
    background: #fff;
}
.container-box {
    background: #f5f7fa;
    min-height: calc(100vh - 96px);
    position: relative;
    display: flex;
    flex-direction: column;
}
/* 自定义滚动条样式 */
::v-deep .el-textarea__inner::-webkit-scrollbar {
    width: 4px;
    /* 滚动条宽度 */
}

::v-deep .el-textarea__inner::-webkit-scrollbar-thumb {
    background-color: #ccc;
    /* 滚动条滑块颜色 */
    border-radius: 4px;
    /* 滚动条滑块圆角 */
}

::v-deep .el-textarea__inner::-webkit-scrollbar-thumb:hover {
    background-color: #999;
    /* 滚动条滑块悬停颜色 */
}

::v-deep .el-textarea__inner::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 滚动条轨道颜色 */
}

::v-deep .el-textarea__inner {
    border-radius: 6px !important;
    height: 125px !important;
}
</style>
